#设计成可以被拖拽的形式,并可以基于此设计基于服务器的东西
#处理一个xml文件
from utils import *
from xml.dom.minidom import parse
dom = parse('src/1.xml')
elem = dom.documentElement
names = elem.getElementsByTagName('name')

x_mins,y_mins,x_maxs,y_maxs=[],[],[],[]

x_mins= elem.getElementsByTagName('xmin')
y_mins= elem.getElementsByTagName('ymin')
x_maxs= elem.getElementsByTagName('xmax')
y_maxs= elem.getElementsByTagName('ymax')
for i in range(len(names)):
    names[i]=names[i].childNodes[0].nodeValue
    x_mins[i]=int(x_mins[i].childNodes[0].nodeValue)
    y_mins[i]=int(y_mins[i].childNodes[0].nodeValue)
    x_maxs[i]=int(x_maxs[i].childNodes[0].nodeValue)
    y_maxs[i]=int(y_maxs[i].childNodes[0].nodeValue)
xml_all_data=[]
for i in range(len(x_mins)):
    xml_all_data.append({names[i]:[x_mins[i],y_mins[i],x_maxs[i],y_maxs[i]]})
print(xml_all_data)

# o=list(xml_all_data[2].values())[0]
# show_with_r("src/1.jpg",o[0],o[1],o[2],o[3])

# p_list=[]
# for i in json_all_data:
#     p_list.append(list(i.values())[0])
# show_with_rs("src/1.jpg",p_list)
height = int(elem.getElementsByTagName('height')[0].childNodes[0].nodeValue)
width = int(elem.getElementsByTagName('width')[0].childNodes[0].nodeValue)

# 将a,[107, 146, 236, 189]转化为b,[x_center,y_center,w,h]
yolo_all_data=[]
for i in range(len(xml_all_data)):
    a=list(xml_all_data[i].values())[0]
    b=[((a[0]+a[2])/2)/width,((a[1]+a[3])/2)/height,(a[2]-a[0])/width,(a[3]-a[1])/height]
    yolo_all_data.append({list(xml_all_data[i].keys())[0]:b})
#print(yolo_all_data)#[{'eyes': [0.162098, 0.424051, 0.121928, 0.109]}, {'eyes': [0.160681, 0.631646, 0.066163, 0.104]}, {'eyes': [0.566163, 0.406329, 0.075614, 0.089]}, {'eyes': [0.577032, 0.589873, 0.038752, 0.091]}, {'eyes': [0.749055, 0.408861, 0.029301, 0.078]}, {'eyes': [0.743384, 0.593671, 0.029301, 0.109]}]


#获取所有类别
with open("src/classes.txt","r")as f:
    all_cata_str=f.read()
all_cata_list=all_cata_str.split("\n")[:-1]#['eyes', 'mouse']
all_cata_dict={}
for i in range(len(all_cata_list)):
    all_cata_dict[all_cata_list[i]]=str(i)
# print(all_cata_dict)#{'eyes': '0', 'mouse': '1'}

#生成yolo标注文件
content=""
for i in range(len(yolo_all_data)):
    content+=all_cata_dict[list(yolo_all_data[i].keys())[0]]+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][0])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][1])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][2])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][3])+"\n"
with open("result/1.txt","w", encoding='utf-8')as f:
    f.write(content)

with open("result/classes.txt","w", encoding='utf-8')as f:
    f.write(all_cata_str)



